import React, { Fragment, useState, useEffect, useRef } from 'react';
import type { FC } from 'react';
import { Anchor, BackTop, message, Badge, Avatar, Typography, Button } from 'antd';
import { ToTopOutlined, LikeOutlined, StarFilled } from '@ant-design/icons';
import { useRequest, useParams } from 'umi';
import { Line, Chart, Legend } from 'bizcharts';
import style from './index.less';
import 'highlight.js/styles/github.css'; // 引入github风格的代码高亮样式
import 'github-markdown-css'; // 引入github的markdown主题样式
import 'react-markdown-editor-lite/lib/index.css';
import { nextDay } from '@/utils/nextDay';
import { getArticle, updateArticle } from './service';
import hljs from 'highlight.js'; // 引入highlight.js库
// import 'highlight.js/styles/github.css'; // 引入github风格的代码高亮样式
import { marked } from 'marked';
import remarkGfm from 'remark-gfm';
import moment from 'moment';
import { ModalForm, ProFormInstance, ProFormText } from '@ant-design/pro-form';
const { Title } = Typography;
const { Link } = Anchor;
// import './github-markdown.css'
// npm i --save-dev @types/marked
const TurndownService = require('turndown').default;
// import * as aaa from 'turndown'
// npm install -g markedç
/**
 * turndown    https://www.npmjs.com/package/turndown
 * @returns
 */
const Detail: FC<Record<string, any>> = props => {
  const [ht, setHt] = useState('');
  const [articleId, setArticleId] = useState('');
  const [liked, setLiked] = useState({});
  const [collect, setCollect] = useState({});
  const [pvData, setPvData] = useState();
  const [collectStatus, setCollectStatus] = useState(true);
  const [titlePart, setTitlePart] = useState({});
  const [show, setShow] = useState(true);
  const restFormRef = useRef<ProFormInstance>();
  const formRef = useRef<ProFormInstance>()
  marked.setOptions({
    renderer: new marked.Renderer(),
    highlight(code, language) {
      if (language && hljs.getLanguage(language)) {
        try {
          return `<br/><pre><code class="hljs language-${language}">${
            hljs.highlight(code, { language }).value
          }</code></pre>`;
        } catch (__) {}
      }
    },
    gfm: true, // 允许 Git Hub标准的markdown.
    pedantic: false, // 不纠正原始模型任何的不良行为和错误（默认为false）
    sanitize: false, // 对输出进行过滤（清理），将忽略任何已经输入的html代码（标签）
    breaks: false, // 允许回车换行（该选项要求 gfm 为true）
    smartLists: true, // 使用比原生markdown更时髦的列表
    smartypants: false, // 使用更为时髦的标点
  });
  const username = localStorage.getItem('username');
  const { id } = useParams();

  useEffect(() => {
    getArticle({ id }).then(res => {
      const data = res.data[0];
      const { html } = data;
      html.replace(/ /gi, ' ');
      setHt(html);
      setTitlePart(data);
    });
    setArticleId(id);
  }, []);
  // 审核状态(0:未审核1:审核通过2:审核未通过)
  const checkPass = async () => {
    const {
      res: { code },
    } = await updateArticle({ id, check: 1,verifier:username });
    if (code === 1000) {
      message.success('文章审核通过');
      setTimeout(function () {
        history.go(-1);
      }, 2000);
    } else {
      message.error('文章审核异常');
    }
  };
  return (
    <div className={style.container}>
      <div className={style.left} />
      <div className={style.center}>
        <div className={style.head_container}>
          <h1 title="top">
            <strong>{titlePart.title}</strong>
          </h1>
          <div className={style.info_con}>
            <Avatar src={titlePart.cover} className={style.photo} />
            <div className={style.text}>
              <div className={style.username}>{titlePart.username}</div>
              <div className={style.date}>{titlePart.updatedAt}</div>
            </div>
            <div className={style.editor} />
          </div>
          <div className={style.cover_container}>
            {titlePart.cover && <img src={titlePart.cover} />}
          </div>
        </div>
        <div dangerouslySetInnerHTML={{ __html: marked(ht) }} className={style.detail_container} />
        <BackTop>
          <div style={{ width: 50, height: 40, fontSize: 20, textAlign: 'center' }}>
            <ToTopOutlined />
            <div style={{ fontSize: 10 }}>回到顶部</div>
          </div>
        </BackTop>
      </div>
      <div className={style.right}>
        <div className={style.chart_con}>
          <Button
            className={style.btn}
            type="primary"
            onClick={() => {
              checkPass();
            }}
            disabled={titlePart?.check !== 0}
          >
            审核通过
          </Button>
          <ModalForm
            title="新建表单"
            formRef={restFormRef}
            trigger={ <Button
              className={style.btn}
              danger
              type="primary"
              // disabled={titlePart?.check !== 0}
            >
              不予审核
            </Button>}
            submitter={{
              searchConfig: {
                submitText: '确认',
                resetText: '取消',
              },
            }}
            onFinish={async values => {
              const {
                res: { code },
              } = await updateArticle({...values,check:2,id:id,verifier:username}) 
              if(code===1000){
                message.success('提交成功');
                history.go(-1)
              }else{
                message.error('提交失败');
              } 
              restFormRef.current?.resetFields();
              return true;
              
            }}
          >
            <ProFormText
              width="lg"
              name="reason"
              label="审核失败原因"
              tooltip="最长为 24 位"
              placeholder="请输入审核失败原因"
            />

          </ModalForm>
        </div>
      </div>
    </div>
  );
};
export default Detail;
